package chapter12.eg2;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class LoginAuthReqHandler extends SimpleChannelInboundHandler<NettyMessage> {

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ctx.writeAndFlush(buildLoginReq());
  }

  private NettyMessage buildLoginReq() {
    NettyMessage message = new NettyMessage();
    Header header = new Header();
    header.setType(MessageType.LOGIN_REQ.value());
    message.setHeader(header);
    return message;
  }

  @Override
  protected void channelRead0(ChannelHandlerContext ctx, NettyMessage message) throws Exception {
    if (message.getHeader() != null
      && message.getHeader().getType() == MessageType.LOGIN_RESP.value()) {
      byte loginResult = (byte) message.getBody();
      if (loginResult != (byte) 0) {
        ctx.close();
      } else {
        System.out.println("Login is ok: " + message);
        ctx.fireChannelRead(message);
      }
    } else {
      ctx.fireChannelRead(message);
    }
  }

  @Override
  public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    ctx.fireExceptionCaught(cause);
  }
}
